//
//  SYComposeTextView.swift
//  YANAWeibo
//
//  Created by mac on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

// 实时看到xib效果
@IBDesignable
class SYComposeTextView: UITextView {
    
     // MARK: --懒加载站位文本
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "😂😂😂😂😂😂😂😂😂😂😂😂"
        label.numberOfLines = 0
        label.textColor = UIColor.lightGrayColor()
        return label
    }()
    
    // 让属性在xib中显示
    @IBInspectable var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    override var font: UIFont? {
        didSet {
            if font == nil {
                return
            }
            placeHolderLabel.font = font
        }
    }
    
    override var text: String? {
        didSet {
            placeHolderLabel.hidden = hasText()
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        // 监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
    }
    
    // 支持xib
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
        // 监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        
    }
    
    private func setupUI() {
        addSubview(placeHolderLabel)
        // 使用系统的约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 指定位置
        placeHolderLabel.x = 5
        placeHolderLabel.y = 8
        
    }
    
    @objc private func textChange() {
        placeHolderLabel.hidden = hasText()
    }
    
    // 移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    

}
